package xhwl.insurance.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.Collection;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.BitmapUtil;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.Constant;
import xhwl.insurance.R;
import xhwl.insurance.customView.CircleImageView;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.customView.PopSelectPic.PopSelectBtnClickListener;
import xhwl.insurance.customView.SelectDialog;
import xhwl.insurance.dialog.UpdateNameDialog;
import xhwl.insurance.event.EventBean;
import xhwl.insurance.http.api.UpdateInfoApi;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.ImgEvent;
import xhwl.insurance.http.bean.resp.ResponseError;
import xhwl.insurance.util.ImgTools;
import xhwl.insurance.util.IntentConstants;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by chengang on 2017/7/26.
 * 个人中心
 */

public class PersonalCenterActivity extends BaseActivity implements View.OnClickListener, PopSelectBtnClickListener {
    private static final String TAG = PersonalCenterActivity.class.getSimpleName();
    private CircleImageView img_header;
    private TextView tv_nickname;
    private TextView tv_nicksex;
    private TextView tv_telephone;
    private String base64;
    private Bitmap bitmap;
    private Bitmap mybitmap;
    private static final int TAKE_PICTURE = 0x000000;
    private String path;
    private RelativeLayout update_imgheader;
    private LinearLayout update_nickname;
    private LinearLayout update_sex;
    private SelectDialog selectDialog;
    private String sexStr = "0";
    String memberinfo = "member_name";
//    private static String[] PERMISSION = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private UpdateNameDialog pd;
    private EditText update_txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void setUpTitleView() {
        titleTextView.setText("个人中心");
        super.setUpTitleView();
    }

    @Override
    public void initViews() {
        initTitleViews();
        img_header = (CircleImageView) findViewById(R.id.img_header);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_nicksex = (TextView) findViewById(R.id.tv_nicksex);
        tv_telephone = (TextView) findViewById(R.id.tv_telephone);
        update_imgheader = (RelativeLayout) findViewById(R.id.update_imgheader);
        update_nickname = (LinearLayout) findViewById(R.id.update_nickname);
        update_sex = (LinearLayout) findViewById(R.id.update_sex);
    }

    @Override
    public void initListener() {
        update_imgheader.setOnClickListener(this);
        update_nickname.setOnClickListener(this);
        update_sex.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.update_imgheader:
                PopSelectPic pop = new PopSelectPic(PersonalCenterActivity.this, update_imgheader);
                pop.setCallBack(PersonalCenterActivity.this);
                break;
            case R.id.update_nickname:
                pd = new UpdateNameDialog(PersonalCenterActivity.this);
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);

                View dialog = View.inflate(PersonalCenterActivity.this, R.layout.dialog_update_name, null);
                TextView cancel = (TextView) dialog.findViewById(R.id.btn_cancel);
                TextView confirm = (TextView) dialog.findViewById(R.id.btn_confirm);
                update_txt = (EditText) dialog.findViewById(R.id.update_txt);
                pd.setContentView(dialog);
                if (tv_nickname.getText().toString() != null) {
                    update_txt.setText(tv_nickname.getText().toString());
                }

                pd.show();
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ("".equals(update_txt.getText().toString().trim())) {
                            ToastUtil.showToast(mContext, "名字不能为空！");
                            return;
                        }
                        updateNameInfo(memberinfo, update_txt.getText().toString().trim());
                    }

                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        pd.dismiss();
                    }
                });

                break;
            case R.id.update_sex:
                sexDialog();
                break;
        }
    }


    @Override
    public void loadData() {
        String headUrl = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_PIC, "");
        String iphone = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.LINK_MOBILE, "");
        String name = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_NAME, "");
        String sex = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_SEX, "");
        ImgTools.getInstance().getRadiusImgFromNetByUrl(headUrl, img_header, R.drawable.touxiang, 180);
        tv_nickname.setText(name);
        tv_nicksex.setText(sex);
        tv_telephone.setText(iphone);
    }

    public void takePhoto() {
//        if (PermisionUtils.islacksOfPermission(PersonalCenterActivity.this, PERMISSION[0])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将影响拍照功能无法使用");
//            ActivityCompat.requestPermissions(this, PERMISSION, 0);
//        } else {
//            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//            File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
//            if (!vFile.exists()) {
//                File vDirPath = vFile.getParentFile();
//                vDirPath.mkdirs();
//            } else {
//                if (vFile.exists()) {
//                    vFile.delete();
//                }
//            }
//            path = vFile.getPath();
//            Uri cameraUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                cameraUri = FileProvider.getUriForFile(this.getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
//            } else {
//                cameraUri = Uri.fromFile(vFile);
//            }
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
//            startActivityForResult(openCameraIntent, TAKE_PICTURE);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestTakePicPermission();
    }

    private void requestTakePicPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(PersonalCenterActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PICTURE:

                ImageItem item = new ImageItem();
                item.sourcePath = path;
                XHLog.e(path);
                bitmap = BitmapUtil.compressImage(path);
                if (bitmap != null) {
                    base64 = BitmapUtil.bitmapToBase64(BitmapUtil.compressImage(bitmap, 60, 200));
                    uploadheader();
                    Constant.TEMP = 0;
                    EventBus.getDefault().post(new ImgEvent(BitmapUtil.compressImage(bitmap, 60, 200), null));
                }
                break;
        }

//        if (requestCode == 3) {
//            if (resultCode == 3) {
//                tv_nickname.setText(data.getStringExtra("nickname"));
//
//            }
//        }
        if (requestCode == 4) {
            if (resultCode == 4) {
                tv_nicksex.setText(data.getStringExtra("nicksex"));
            }
        }

        super.onActivityResult(requestCode, resultCode, data);

    }

    public void uploadheader() {
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        ;
        if (StringUtil.isEmpty(memberId)) {
            return;
        }
        UpdateInfoApi api = new UpdateInfoApi(memberId, "member_pic", "data:image/png;base64," + base64);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ResponseError>() {
            @Override
            public void onNext(ResponseError responseError) {
                if (responseError.isSuccess()) {
                    Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
                    img_header.setImageBitmap(bitmap);
                    Constant.TEMP = 0;
                    EventBus.getDefault().post(new EventBean());
                    EventBus.getDefault().post(new ImgEvent(mybitmap, null));
                }
            }
        });
    }

    @Override
    public void onTakePhotoClick() {
        takePhoto();

    }

    @Override
    public void onSelectPicClick() {
        pickPicture();

    }

    public void pickPicture() {
//        if (PermisionUtils.islacksOfPermission(this, PERMISSION[1])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将无法选择您的照片");
//            ActivityCompat.requestPermissions(this, PERMISSION, 1);
//        } else {
//            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
//            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
//            startActivity(intent);
//
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestPermission();
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
                    startActivity(intent);
                } else {
                    Log.e(TAG, "用户拒绝开启权限");
                    PermisionUtils.dialog(PersonalCenterActivity.this, "用户拒绝开启权限");
                }
            }
        });
    }
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            bitmap = BitmapUtil.compressImage(item.getSourcePath());
            img_header.setImageBitmap(bitmap);
            base64 = BitmapUtil.bitmapToBase64(BitmapUtil.compressImage(bitmap, 60, 200));
            uploadheader();
        }
    }

    private void sexDialog() {
        View sexView = LayoutInflater.from(this).inflate(R.layout.sex_selection_dialog, null);
        TextView cancel = (TextView) sexView.findViewById(R.id.cancel);
        TextView confirm = (TextView) sexView.findViewById(R.id.confirm);
        final TextView male = (TextView) sexView.findViewById(R.id.male);
        final TextView female = (TextView) sexView.findViewById(R.id.female);

        selectDialog = new SelectDialog(PersonalCenterActivity.this, sexView, Gravity.BOTTOM);
        selectDialog.setCanceledOnTouchOutside(false);
        selectDialog.show();

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectDialog.cancel();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectDialog.cancel();
                if ("0".equals(sexStr)) {
                    updateInfo("member_sex", "0");
                } else {
                    updateInfo("member_sex", "1");
                }
            }
        });

        male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sexStr = "0";
                male.setBackgroundResource(R.color.divider_bg);
                female.setBackgroundResource(R.color.white);
            }
        });

        female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sexStr = "1";
                male.setBackgroundResource(R.color.white);
                female.setBackgroundResource(R.color.divider_bg);
            }
        });
    }

    private void updateInfo(String column_name, String column_value) {
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        ;
        if (StringUtil.isEmpty(memberId)) {
            return;
        }

        UpdateInfoApi api = new UpdateInfoApi(memberId, column_name, column_value);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ResponseError>() {
            @Override
            public void onNext(ResponseError responseError) {
                if (responseError.isSuccess()) {
                    Toast.makeText(mContext, "修改成功", Toast.LENGTH_SHORT).show();
                    if ("0".equals(sexStr)) {
                        tv_nicksex.setText("男");
                    } else {
                        tv_nicksex.setText("女");
                    }
                    EventBus.getDefault().post(new EventBean());
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri = Uri.fromFile(vFile);
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, 0);
                } else {
                    ToastUtil.showToast(PersonalCenterActivity.this, "拍照");
                }

                break;
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(PersonalCenterActivity.this, "读取手机存储");
                }
                break;
        }
    }


    private void updateNameInfo(String column_name, String column_value) {
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        if (StringUtil.isEmpty(memberId)) {
            return;
        }

        UpdateInfoApi api = new UpdateInfoApi(memberId, column_name, column_value);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ResponseError>() {
            @Override
            public void onNext(ResponseError responseError) {
                if (responseError.isSuccess()) {
                    Constant.TEMP = 1;
                    Toast.makeText(mContext, "修改成功", Toast.LENGTH_SHORT).show();
                    tv_nickname.setText(update_txt.getText().toString());
                    pd.dismiss();
                }
            }
        });
    }
}
